<template>
    <Dialog :app-dialog="appDialog">
        <el-scrollbar max-height="600px" class="upload-file">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="110px" style="padding-right: 20px">
                <!-- 分组 -->
                <el-form-item label="分组">
                    <el-cascader
                        ref="cascaderRef"
                        v-model="form.group_id"
                        style="width: 100%"
                        :options="groupData"
                        :props="defaultProps"
                        placeholder="请选择分组"
                        @change="orgChange" />
                </el-form-item>
                <!-- 类型 -->
                <el-form-item label="类型" class="form-radio">
                    <el-radio-group v-model="form.type" class="radio_list" @change="changeType">
                        <el-radio
                            v-for="item in typeDiff"
                            :key="item.value"
                            :label="item.value"
                            class="radio_list_item"
                            :disabled="item.disabled">
                            <span class="radio_list_item_text">{{ item.name }}</span>
                            <el-tooltip v-if="item.value === 1" :content="item.text" placement="bottom">
                                <div class="radio_list_item_icon radio_img">
                                    <img src="@/assets/image/material/question.png" alt="" />
                                </div>
                            </el-tooltip>
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- 上传文件 -->
                <ZWUpload
                    ref="emptyData"
                    :key="componentKey"
                    :files="'files'"
                    :tips="tips"
                    :accept="accept"
                    @submit="getFileList"
                    @del="del" />
                <el-form-item>
                    <template #label>
                        <div class="label_text">
                            <span>素材标签</span>
                            <el-tooltip :content="tagTips.materialTagTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="tagIdsRef" v-model="form.tag_ids" />
                </el-form-item>
                <el-form-item v-if="form.type == 1" label="是否强制授权">
                    <el-radio-group v-model="form.is_force_grant" @change="changeAuth">
                        <el-radio :label="1">否</el-radio>
                        <el-radio :label="2">是</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-show="form.is_force_grant == 2 && form.type == 1" label="授权内容">
                    <el-checkbox-group v-model="form.grant_params">
                        <el-checkbox label="offical_headimg_nickname">头像昵称（公众号）</el-checkbox>
                        <el-checkbox label="phone">手机号（小程序）</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item v-if="form.type == 1">
                    <template #label>
                        <div class="label_text">
                            <span>浏览打标</span>
                            <el-tooltip :content="tagTips.browseCustTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="viewtagIdsRef" v-model="form.view_tag_ids" :type="2" />
                </el-form-item>
                <el-form-item v-if="form.type == 1">
                    <template #label>
                        <div class="label_text">
                            <span>分享打标</span>
                            <el-tooltip :content="tagTips.shareCustTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="shareTagIdsRef" v-model="form.share_tag_ids" :type="2" />
                </el-form-item>
                <el-form-item label="">
                    <div class="agree_ment">
                        <!-- 暂时隐藏掉,协议要先不上需要法务确认 -->
                        <!-- <el-checkbox v-model="form.check" @change="confirmSure"></el-checkbox>
            <span class="ml2">勾选代表同意</span>
            <el-link class="form-link" type="primary" :underline="false">《***用户协议》</el-link> -->
                    </div>
                </el-form-item>
            </el-form>
        </el-scrollbar>
    </Dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch, onUnmounted, onMounted } from 'vue';
import Dialog from '@/components/Dialog.vue';
import ZWUpload from './ZWUpload.vue';
import selectTags from '../../../components/selectTags.vue';
import { createdFile, getFileInfo, updateFile, getGroupList } from '@/api/concreation';
import { ElForm, ElMessage } from 'element-plus';
import { getSetionId } from '@/utils/utils';
import bus from '@/utils/bus';
import { useStore } from '@/store';
import { endLoading, startLoading } from '@/utils/request';

const formRef = ref<InstanceType<typeof ElForm>>();
const cascaderRef: any = ref(null); // 选择分组ref
const emit = defineEmits(['submit']);
const props = defineProps(['groupId', 'type']);
const store = useStore();
const uploadSelectRef = ref(null);
const uploadTitle = ref('上传文件');
const uploadVisib = ref(false);
const isEdit = ref(false);
const emptyData = ref(); // 清空回显数据
const componentKey = ref(0);
const tagType = ref(1);
const tagTips = {
    materialTagTips: '该素材会被打上此素材标签，在列表上会展示',
    browseCustTips: '浏览该素材的客户将被打上此客户标签',
    shareCustTips: '点击该素材的分享按钮并生成分享链接的客户将被打上此客户标签'
};
const tagIdsRef = ref(null);
const viewtagIdsRef = ref(null);
const shareTagIdsRef = ref(null);

const tips = computed(() => {
    let te = '格式支持DOC、DOCX、XLS、XLSX、PPT、PPTX、PDF格式，文件大小不超过20M';
    if (form.type == 1) {
        te = '格式支持DOCX、XLS、XLSX、PPTX、PDF格式，文件大小不超过20M';
    }
    return te;
});
const accept = computed(() => {
    let te = '.DOC,.DOCX,.XLS,.XLSX,.PPT,.PPTX,.PDF';
    if (form.type == 1) {
        te = '.DOCX,.XLS,.XLSX,.PPTX,.PDF';
    }
    return te;
});

//上传弹框
const uploadInfo = computed(() => {
    return store.getters['content/upload'];
});
// 分组列表
const groupData = ref([]);

/**
 * @description: 获取分组数据
 * @return {*}
 */
const getGroupListFunc = async () => {
    const res = await getGroupList({ type: props.type });
    groupData.value = res.data;
};
//标签
const tags = computed(() => {
    return store.getters['content/tagsInfo'].tags;
});
const defaultProps = {
    checkStrictly: true,
    emitPath: false,
    label: 'name',
    value: 'id'
};
const form = reactive({
    tag_ids: [],
    view_tag_ids: [],
    is_force_grant: 1,
    group_id: '', //分组
    type: 0,
    files: '', //文件
    tags: [], //标签
    check: true, //用户协议
    title: '', //标题
    id: '', //内容id
    share_tag_ids: [],
    grant_params: ['offical_headimg_nickname', 'phone']
});

const changeType = (val: any) => {
    if (val == 0) {
        form.is_force_grant = '';
    } else if (val == 1) {
        form.is_force_grant = 1;
    }
    form.files = '';
    emptyData.value.empty();
    formRef.value.resetFields();
};

const rules = reactive({
    title: [
        {
            required: true,
            message: '标题不能为空',
            trigger: 'blur'
        }
    ],
    files: [
        {
            required: true,
            message: '文件不能为空',
            trigger: 'click'
        }
    ]
});
const typeDiff = reactive([
    { value: 0, name: `普通文件` },
    {
        value: 1,
        name: `雷达文件`,
        text: `雷达文件可以追踪客户端浏览次数、时间等数据`,
        disabled: false
    }
]);

// 获取上传成功的文件
const getFileList = (data: any) => {
    try {
        if (data.length) {
            const arr: any[] = getSetionId('code', data);
            form.files = arr[0];
        } else {
            form.files = '';
        }
    } catch (error) {
    } finally {
        endLoading();
    }
};
const changeAuth = () => {
    if (form.is_force_grant == 1) {
        form.grant_params = [];
    } else {
        form.grant_params = ['offical_headimg_nickname', 'phone'];
    }
};
const del = () => {
    typeDiff[1].disabled = false;
    form.files = '';
};
// 取消
const cancelHandel = () => {
    appDialog.visible = false;
    isEdit.value = false;
    typeDiff[1].disabled = false;
    delUpform();
    // bus.emit('delUpform')
    formRef.value.resetFields();
};
//确定
const submitHandel = async () => {
    await formRef.value.validate();
    try {
        const groupId = form.group_id;
        const grant = {
            offical_headimg_nickname: form.grant_params.includes('offical_headimg_nickname') ? 2 : 1,
            phone: form.grant_params.includes('phone') ? 2 : 1
        };
        const params = {
            title: form.title,
            group_id: form.group_id,
            file_type: form.type,
            code: form.files,
            tag_ids: getSetionId('id', form.tag_ids),
            view_tag_ids: getSetionId('id', form.view_tag_ids),
            media_content_id: form.id,
            is_force_grant: form.is_force_grant,
            grant_params: grant,
            share_tag_ids: getSetionId('id', form.share_tag_ids)
        };
        if (form.type === 0) {
            delete params.view_tag_ids;
            delete params.share_tag_ids;
        }
        startLoading();
        isEdit.value ? await updateFile(params) : await createdFile(params);
        ElMessage.success(`${isEdit.value ? '修改' : '上传'}文件成功`);
        emit('submit', { id: groupId });
        cancelHandel();
        forceRerender();
    } catch (error) {
        endLoading();
    }
};
const forceRerender = () => {
    componentKey.value += 1;
};
const appDialog = reactive({
    visible: uploadVisib,
    title: uploadTitle,
    width: '670px',
    cancel: cancelHandel,
    submit: submitHandel,
    isDisable: false,
    cancelText: '取消',
    submitText: '保存'
});
const confirmSure = (val: boolean) => {
    appDialog.isDisable = !val;
};
//获取编辑内容
const editItem = (data: any) => {
    uploadTitle.value = data.title;
    uploadVisib.value = data.uploadVisib;
    if (uploadVisib.value) {
        getGroupListFunc();
    }
    form.grant_params = ['offical_headimg_nickname', 'phone'];
    form.is_force_grant = 1;
    form.type = 0;
    form.check = true;
    if (data.isPdf) {
        typeDiff[1].disabled = true;
    } else {
        typeDiff[1].disabled = false;
    }
    if (!data.isEdit) return;
    isEdit.value = data.isEdit;
    const params = {
        media_content_id: data.media_content_id
    };
    //获取文件详情
    getFileInfo(params).then((data: any) => {
        // tag_ids 素材标签
        // view_tag_ids 浏览客户标签
        // share_tag_ids 分享客户标签
        form.tag_ids = data.tag_info;
        form.view_tag_ids = data.view_tag_info;
        form.share_tag_ids = data.share_tag_info;
        form.title = data.title;
        form.group_id = data.group_id;
        form.tags = data.tagInfo;
        form.type = data.is_radar;
        form.id = data.id;
        form.files = data.mediaFileInfo.code;
        form.is_force_grant = data.is_force_grant;
        form.grant_params = [];
        if (data.grant_params?.offical_headimg_nickname == 2) {
            form.grant_params.push('offical_headimg_nickname');
        }
        if (data.grant_params?.phone == 2) {
            form.grant_params.push('phone');
        }
        emptyData.value.echo(data.mediaFileInfo);
        setTimeout(() => {
            tagIdsRef.value?.init();
            viewtagIdsRef.value?.init();
            shareTagIdsRef.value?.init();
        }, 0);
    });
};
// 清空上传表单数据
const delUpform = () => {
    Object.keys(form).map(key => {
        delete form[key];
    });
    emptyData.value.empty();
};
bus.on('delUpform', delUpform);
bus.on('editItem', editItem);
// watch(
//   () => uploadInfo.value,
//   (uploadInfo) => {
//     console.log(uploadInfo, '====uploadInfo')
//     uploadTitle.value = uploadInfo.title
//     uploadVisib.value = uploadInfo.uploadVisib
//     form.type = 0
//     form.check = true
//     if (uploadInfo.ext == '.pdf') {
//       typeDiff[1].disabled = true
//     } else {
//       typeDiff[1].disabled = false
//     }
//   },
//   { immediate: true }
// )
const prop_group = () => {
    props.groupId ? (form.group_id = props.groupId) : (form.group_id = 0);
};
watch(
    () => props.groupId,
    val => {
        form.group_id = val;
    },

    { immediate: true }
);
watch(tags, data => (form.tags = data));
watch(
    () => form.files,
    () => formRef.value.validateField('files')
);
// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};
defineExpose({ prop_group });
onUnmounted(() => {
    bus.off('editItem', editItem);
});
</script>
<style lang="scss" scoped>
.upload-file {
    padding-top: 14px;

    .form-radio {
        line-height: normal;

        :deep(.el-form-item__label),
        :deep(.el-form-item__content) {
            line-height: normal;
        }

        .el-radio {
            height: auto;
        }
    }
}

.radio_list {
    &_item {
        &_icon {
            width: 14px;
            height: 14px;
            margin: -3px 0 0 6px;

            img {
                margin-top: 2px;
                width: 100%;
                height: 100%;
                vertical-align: top;
            }
        }
    }

    :deep .el-radio__label {
        display: flex;
        align-items: center;
    }
}

.ml2 {
    margin-left: 2px;
}

.mr10 {
    margin-right: 10px;
}

.agree_ment {
    display: flex;
    align-items: center;
}

:deep .el-scrollbar {
    height: 50%;
}

:deep(.el-form-item) {
    .label_text {
        display: flex;
        align-items: center;
        gap: 6px;

        img {
            width: 14px;
            height: 14px;
        }
    }
}
</style>
